import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { getClientInfo } from './client_info'
import packageConfig from '../../package'
import { errors } from '../api/error'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})
service.defaults.headers.post['Content-Type'] = 'application/json'
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = JSON.stringify({ 'token': getToken() })
    config.headers['clientInfo'] = getClientInfo()
  }
  let req_model = {
    appName: packageConfig.name,
    format: '',
    sign: '',
    source: 'crec_front_web',
    timestamp: '',
    version: packageConfig.version
  }
  req_model.timestamp = new Date().getTime().toString()

  switch (config.method) {
    case 'post':
      req_model.param = config.data
      config.data = req_model
      break
    case 'get':
      break
  }
  return config
}, error => {
  Message({
    message: '请求异常 ' + error.message,
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  if (response.config.responseType === 'blob') {
    if (response.config.filetype === 'pdf') {
      return response.data
    } else {
      return response
    }
  }
  const res = response.data
  if (res.code === 200 || res.errorCode == 0 || res.rtn == 0) { // 订单详情  //rtn 售后订单
    return res
  }
  if (response.config.responseType === 'pdf') {
    return res
  }
  // ---待定安页面定案失败错误码-450
  if (res.code == -450) {
    Message({
      message: res.result,
      type: 'error',
      duration: 3 * 1000
    })
    return
  }
  if (res.code !== '0') {
    if (res.code !== '-112') {
      Message({
        message: exception(res.code, res.message),
        type: 'error',
        duration: 3 * 1000
      })
    }
    if (res.code === '-2') {
      store.dispatch('FedLogOut').then(() => {
        location.reload()
      })
    }
    return Promise.reject({ e: 'error' })
  } else {
    return response.data
  }
}, error => {
  let code = ''
  if (error.response) {
    code = error.response.status
  } else {
    code = '网络已断开'
  }
  Message({
    message: '网络不给力(' + code + ')',
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

function exception(code, message) {
  const list = errors.filter(e => {
    return e.code === code
  })
  if (list.length === 0) {
    return message
  } else {
    return list[0].message
  }
}
export default service
